/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package course.providers.jpa;

import course.entities.Record;
import course.entities.UserActivity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author def
 */
@Stateless
public class RecordProvider implements Serializable {

    private static final long serialVersionUID = -465846834631123400L;

    @PersistenceContext(unitName = "webPartPU")
    protected EntityManager em;

    public RecordProvider() {
    }

    public Record create() {
        Record entity = new Record();
        em.persist(entity);
        return entity;
    }

    public void update(Record entity) {
        em.merge(entity);
    }

    public void delete(Record entity) {
        em.remove(em.merge(entity));
    }

    public Record findById(long id) {
        return (Record) em.find(Record.class, id);
    }

    public List<Record> findAll() {
        Query q = em.createNamedQuery("Record.findAll");
        return (List<Record>) q.getResultList();
    }

    public List<Record> findRecordsByUserId(long id) {
        Query q = em.createQuery("SELECT ua FROM UserActivity ua WHERE ua.user.id = :userId");
        q.setParameter("userId", id);
        List<UserActivity> activityList = (List<UserActivity>) q.getResultList();
        List<Record> records = new ArrayList<>();
        Iterator<UserActivity> activityIterator = activityList.iterator();
        while (activityIterator.hasNext()) {
            records.addAll(activityIterator.next().getRecordList());
        }
        return records;
    }

}
